package com.fish.service.impl.account;

import java.util.Date;
import java.util.List;

import com.fish.account.dao.AccountDAO;
import com.fish.account.dao.BalanceDAO;
import com.fish.account.dao.RechargesDAO;
import com.fish.account.po.Account;
import com.fish.account.po.Balance;
import com.fish.account.po.Recharges;
import com.fish.common.constant.QueryPage;
import com.fish.service.account.RechargesService;
import com.fish.utils.UUIDGenerator;

public class RechargesServiceImpl implements RechargesService {
	private RechargesDAO rechargesDAO;
	private BalanceDAO balanceDAO;
	private AccountDAO accountDAO;
	
	@Override
	public Recharges queryRechargesByPrimaryKey(Recharges recharges) {
		return rechargesDAO.queryRechargesByPrimaryKey(recharges);
	}

	@Override
	public void insertRecharges(Recharges recharges) {
		rechargesDAO.insertRecharges(recharges);
	}

	@Override
	public void updateRecharges(Recharges recharges) {
		recharges.setUpdateTime(new Date());
		rechargesDAO.updateRecharges(recharges);
		Balance userBalance = this.balanceDAO.queryBalanceByUser(recharges.getUserId());
		if(userBalance==null) {
			userBalance = new Balance();
			userBalance.setBalance(0.0);
		}
		Double currentUserBalance = userBalance.getBalance() + Double.valueOf(recharges.getTotalFee());
		
		Account userAccount = new Account();
		userAccount.setAccountId(UUIDGenerator.getNewUUID());
		userAccount.setAmount(Double.valueOf(recharges.getTotalFee()));
		userAccount.setBalance(currentUserBalance);
		userAccount.setContent("平台充值");
		userAccount.setOperateTime(new Date());
		userAccount.setType("RECHARGE");
		userAccount.setUserId(recharges.getUserId());
		userAccount.setOrderId(recharges.getTradeNo());
		accountDAO.insertAccount(userAccount);
		
		userBalance.setLastBalance(userBalance.getBalance());
		userBalance.setBalance(currentUserBalance);
		userBalance.setUserId(recharges.getUserId());
		Balance init = balanceDAO.queryBalanceByUser(recharges.getUserId()); 
		if(init==null) {
			userBalance.setBalanceId(UUIDGenerator.getNewUUID());
			this.balanceDAO.insertBalance(userBalance);
		} else {
			this.balanceDAO.updateByUser(userBalance);
		}
	}

	public void setRechargesDAO(RechargesDAO rechargesDAO) {
		this.rechargesDAO = rechargesDAO;
	}

	@Override
	public Long queryRechargesCountByObject(Recharges recharges) {
		return this.rechargesDAO.queryRechargesCountByObject(recharges);
	}

	@Override
	public List<Recharges> queryRechargesByObject(Recharges recharges, QueryPage queryPage) {
		return this.rechargesDAO.queryRechargesObject(recharges,queryPage);
	}

	public void setBalanceDAO(BalanceDAO balanceDAO) {
		this.balanceDAO = balanceDAO;
	}

	public void setAccountDAO(AccountDAO accountDAO) {
		this.accountDAO = accountDAO;
	}

}
